package com.sap.sap_mangers.service.Impl;

import com.sap.sap_mangers.Vo.Site.SiteUserVo;
import com.sap.sap_mangers.dto.Navigation.AddNavigation;
import com.sap.sap_mangers.dto.Navigation.UpdateNavigation;
import com.sap.sap_mangers.mapper.NavigationMapper;
import com.sap.sap_mangers.pojo.SapNavigation;
import com.sap.sap_mangers.pojo.SapNavigationClassify;
import com.sap.sap_mangers.service.CacheService;
import com.sap.sap_mangers.service.NavigationService;
import com.sap.sap_mangers.until.CosUntil;
import com.sap.sap_mangers.until.JwtUtil;
import com.sap.sap_mangers.until.SimpleJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 樊东升
 * @date 2022/8/19 23:15
 */
@Service
public class NavigationServiceImpl implements NavigationService {
    @Autowired
    private NavigationMapper navigationMapper;

    @Autowired
    private CacheService cacheService;

    @Override
    public List<List<SapNavigation>> getNavigation() {
        Integer navigationClassify = navigationMapper.getNavigationClassify();
        List<List<SapNavigation>> data = new ArrayList<>();
        for (int i = 1; i <= navigationClassify; i++) {
            List<SapNavigation> navigation = navigationMapper.getNavigation(i);
            data.add(navigation);
        }
        return data;
    }

    @Override
    public List<SiteUserVo> getNavigationForUser() {
        List<SiteUserVo> site = new ArrayList<>();
        Integer navigationClassify = navigationMapper.getNavigationClassify();
        List<SapNavigationClassify> sapNavigationClassify = navigationMapper.getSapNavigationClassify();
        Map<Integer,SapNavigationClassify> classifyMap=new HashMap<>(31);
        for (SapNavigationClassify classify : sapNavigationClassify) {
            classifyMap.put(Math.toIntExact(classify.getNavigationClassifyId()),classify);
        }
        for (int i = 1; i <= navigationClassify; i++) {
            SiteUserVo siteUserVo = new SiteUserVo();
            siteUserVo.setTitle(classifyMap.get(i).getNavigationClassifyName());
            List<SapNavigation> navigation = navigationMapper.getNavigation(i);
            siteUserVo.setData(navigation);
            site.add(siteUserVo);
        }
       return site;
    }

    @Override
    public SimpleJson addSapNavigation(AddNavigation addNavigation) {
        CosUntil cosUntil = new CosUntil();
        SapNavigation sapNavigation = new SapNavigation();
        try {
            String cosUrl = cosUntil.getCosUrl(addNavigation.getImage(), "navigation/" + addNavigation.getImage().getOriginalFilename());
            Integer rank = navigationMapper.getRank(addNavigation.getClassify());
            sapNavigation.setNavigationUrl(addNavigation.getUrl());
            sapNavigation.setNavigationUrlName(addNavigation.getUrlName());
            //当note为null的时候我们插入一个空格
            if (addNavigation.getNote() == null) {
                sapNavigation.setNavigationUrlNote(" ");
            } else {
                sapNavigation.setNavigationUrlNote(addNavigation.getNote());
            }
            sapNavigation.setNavigationUsername(JwtUtil.getUserForToken());
            sapNavigation.setNavigationImage(cosUrl);
            sapNavigation.setNavigationName(cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), JwtUtil.getUserForToken()));
            sapNavigation.setNavigationCreateTime(new Timestamp(System.currentTimeMillis()));
            sapNavigation.setNavigationReviseUsername(JwtUtil.getUserForToken());
            sapNavigation.setNavigationReviseName(cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), JwtUtil.getUserForToken()));
            sapNavigation.setNavigationReviseTime(new Timestamp(System.currentTimeMillis()));
            if (rank == null) {
                sapNavigation.setNavigationRank(1);
            } else {
                sapNavigation.setNavigationRank(rank + 1);
            }
            sapNavigation.setNavigationClassifyId(addNavigation.getClassify());
        } catch (IOException e) {
            return new SimpleJson(2, "上传图片出错");
        }
        try {
            navigationMapper.addNavigation(sapNavigation);
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(3, "信息报错出错");
        }
        //并发情况下存在问题(但是这个功能不存在并发问题)
        return new SimpleJson(navigationMapper.getMessageById(navigationMapper.getMessageId()));
    }

    @Override
    public SimpleJson updateNavigation(UpdateNavigation updateNavigation) {
        CosUntil cosUntil = new CosUntil();
        SapNavigation sapNavigation;
        try {
            /*
              这里的逻辑比较复杂
              属实能力有限
              当分类相同时，需要调整rank的和被调整的交换rank即可
              当分类不相同时，先把需要调整rank和classify的哪条记录修改成新的classify然后rank变成新的分类里最高的
              然后把就的分类的rank依次修改
              然后就是新分离里，rank调整顺序
             */
            String cosUrl = null;
            if (updateNavigation.getImage() != null) {
                cosUrl = cosUntil.getCosUrl(updateNavigation.getImage(), "navigation/" + updateNavigation.getImage().getOriginalFilename());
            }
            SapNavigation messageById = navigationMapper.getMessageById(updateNavigation.getId());
            Integer rank = navigationMapper.getRank(updateNavigation.getClassify());
            if (updateNavigation.getClassify() == null) {
                if (updateNavigation.getRank() == null) {
                    sapNavigation = new SapNavigation(updateNavigation.getId(), updateNavigation.getUrl(), updateNavigation.getUrlName(), updateNavigation.getNote(), cosUrl, JwtUtil.getUserForToken(), cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), JwtUtil.getUserForToken()), new Timestamp(System.currentTimeMillis()), null, null);
                    navigationMapper.updateNavigation(sapNavigation);
                }
            } else {
                if (messageById.getNavigationClassifyId().equals(updateNavigation.getClassify())) {
                    if (updateNavigation.getRank() != null) {
                        Integer oldRank = navigationMapper.getOldRank(updateNavigation.getId());
                        SapNavigation idByRankAndClassify = navigationMapper.getIdByRankAndClassify(updateNavigation.getRank(), updateNavigation.getClassify());
                        navigationMapper.updateRank((int) idByRankAndClassify.getNavigationId(), rank + 1);
                        navigationMapper.updateRank(updateNavigation.getId(), updateNavigation.getRank());
                        navigationMapper.updateRank((int) idByRankAndClassify.getNavigationId(), oldRank);
                        sapNavigation = new SapNavigation(updateNavigation.getId(), updateNavigation.getUrl(), updateNavigation.getUrlName(), updateNavigation.getNote(), cosUrl, JwtUtil.getUserForToken(), cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), JwtUtil.getUserForToken()), new Timestamp(System.currentTimeMillis()), updateNavigation.getRank(), updateNavigation.getClassify());
                        navigationMapper.updateNavigation(sapNavigation);
                    }
                } else {
                    if (updateNavigation.getRank() != null) {
                        sapNavigation = new SapNavigation(updateNavigation.getId(), updateNavigation.getUrl(), updateNavigation.getUrlName(), updateNavigation.getNote(), cosUrl, JwtUtil.getUserForToken(), cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), JwtUtil.getUserForToken()), new Timestamp(System.currentTimeMillis()), rank + 1, updateNavigation.getClassify());
                        navigationMapper.updateNavigation(sapNavigation);
                        Integer oldRank = messageById.getNavigationRank();
                        Integer oldRankLimit = navigationMapper.getRank((int) messageById.getNavigationClassifyId());
                        List<SapNavigation> navigation = navigationMapper.getNavigation((int) messageById.getNavigationClassifyId());
                        for (Integer i = oldRank; i <= oldRankLimit; i++) {
                            navigationMapper.updateRank((int) navigation.get(i - 1).getNavigationId(), i);
                        }
                        SapNavigation idByRankAndClassify = navigationMapper.getIdByRankAndClassify(updateNavigation.getRank(), updateNavigation.getClassify());
                        navigationMapper.updateRank((int) idByRankAndClassify.getNavigationId(), rank + 2);
                        navigationMapper.updateRank(updateNavigation.getId(), updateNavigation.getRank());
                        navigationMapper.updateRank((int) idByRankAndClassify.getNavigationId(), rank + 1);
                    }
                }
            }
        } catch (IOException e) {
            return new SimpleJson(2, "上传图片出错");
        }
        return new SimpleJson(navigationMapper.getMessageById(updateNavigation.getId()));
    }

    @Override
    public List<SapNavigationClassify> getSapNavigationClassify() {
        return navigationMapper.getSapNavigationClassify();
    }

    @Override
    public Integer getRank(Integer classify) {
        return navigationMapper.getRank(classify);
    }

    @Override
    public void deleteMessageById(Integer id) {
        navigationMapper.deleteMessageById(id);
    }
}
